from flask import Flask, session, g
from flask_migrate import Migrate
import config
from exts import db, mail
from models import UserModel
from blueprints.qa import bp as qa_bp
from blueprints.auth import bp as auth_bp

app = Flask(__name__)
app.config.from_object(config)  # 加载配置文件

# 初始化扩展
db.init_app(app)  # 数据库初始化
mail.init_app(app)  # 邮件初始化
migrate = Migrate(app, db)  # 数据库迁移工具
# 数据库更改操作
# flask db init 只需执行一次
# flask db migrate 将orm模型生成迁移脚本
# flask db upgrade 将迁移脚本映射到数据库中

# 注册蓝图（模块化路由）
app.register_blueprint(qa_bp)  # 问答模块
app.register_blueprint(auth_bp)  # 认证模块


@app.before_request
# 请求前处理：检查登录状态
def my_before_request():
    user_id = session.get("user_id")  # 从session获取用户ID
    if user_id:
        user = UserModel.query.get(user_id)  # 查询用户信息
        setattr(g, "user", user)
    else:
        setattr(g, "user", None)  # 未登录状态


# 模板上下文：使所有模板能访问user变量
@app.context_processor
def my_context_processor():
    return {"user": g.user}


if __name__ == '__main__':
    app.run(debug=True, threaded=True)
